package Model.DAO;

import Model.ImageUtil;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PictureDao extends BaseDao{

    public PictureDao() {
        super("Picture");
    }

    private void readImage2DB(String path)
    {
        Connection conn = null;
        PreparedStatement ps = null;
        try
        {
            FileInputStream in = ImageUtil.readImage(path);
            conn = dataSource.getConnection();
            String sql = "insert into picture (id,photo)values(?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, 1);
            ps.setBinaryStream(2, in, in.available());
            int count = ps.executeUpdate();
            if (count > 0)
            {
                System.out.println("插入成功！");
            }
            else
            {
                System.out.println("插入失败！");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (null != ps)
            {
                try
                {
                    ps.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
        }

    }

    // 读取数据库中图片
    private void readDB2Image(String targetPath)
    {
        //String targetPath = "C:/Users/Jia/Desktop/mogen.jpg";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try
        {
            conn = dataSource.getConnection();
            String sql = "select * from picture where id =?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, 1);
            rs = ps.executeQuery();
            while (rs.next())
            {
                InputStream in = rs.getBinaryStream("photo");
                ImageUtil.readBin2Image(in, targetPath);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (rs != null)
            {
                try
                {
                    rs.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            if (ps != null)
            {
                try
                {
                    ps.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }

        }
    }
}
